package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.common.RedisConst;
import com.itheima.health.dao.SetMealDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetMealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.*;

/**
 * @author zhangmeng
 * @description 套餐SEVICE实现类
 * @date 2019/9/26
 **/
@Service(interfaceClass = SetMealService.class)
@Slf4j
public class SetMealServiceImpl implements SetMealService {
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private SetMealDao setMealDao;
    @Transactional
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        log.info("[套餐-添加]data:{},checkgroupIds:{}",setmeal,checkgroupIds);
        // 调用DAO数据入库
        // 插入基本数据
        setMealDao.insert(setmeal);
        // 插入关联数据
        for (Integer checkgroupId : checkgroupIds) {
            setMealDao.insertSetMealAndCheckGroup(setmeal.getId(),checkgroupId);
        }
        //图片不为空，则操作redis进行记录
        if(!StringUtils.isEmpty(setmeal.getImg())) {
            try (Jedis jedis = jedisPool.getResource()) {
                jedis.sadd(RedisConst.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());
            }
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //设置分页参数
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        //DAO查询数据
        Page<Setmeal> page = setMealDao.selectByCondition(queryPageBean.getQueryString());
        //封装返回值
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public List<Setmeal> findAll() {
        List<Setmeal> setmeals = new ArrayList<>();
        try (Jedis jedis = jedisPool.getResource()) {
            //获取键的值
            String findOrders = jedis.get("health_Orders");
            ObjectMapper mapper = new ObjectMapper();
            //判断redis里是否存在不数据
            if(findOrders == null){
                //没有 查询数据库  然后存入redis
                setmeals = setMealDao.selectAll();
                String findOrderJson = mapper.writeValueAsString(setmeals);
                jedis.setex("health_Orders",24*60*60,findOrderJson);
            }else {
                //有 直接冲redis里查询
                setmeals = mapper.readValue(findOrders, List.class);
                log.info("使用Redis缓存 返回数据成功");
            }
        } catch (IOException e) {
            log.error("",e);
        }
        return setmeals;
    }

    @Override
    public Setmeal findById(Integer id) {
        //调用DAO查询数据
        Setmeal setmeal = null;

        try (Jedis jedis = jedisPool.getResource()) {
            //查询redis键的值
            Set<String> findOrderSet = jedis.smembers("healthOrder");
            ObjectMapper mapper = new ObjectMapper();
            //判断redis里是否存在数据
            if(findOrderSet.size() > 0) {
                //如果有  遍历 查询数据内是否存在 与要查询的Id相对应的数据
                for (String findOrder : findOrderSet) {
                    setmeal = mapper.readValue(findOrder, Setmeal.class);
                    if (setmeal.getId() == id) {
                        return setmeal;
                    }
                }
            }
            //不存在 去数据库取  然后 存入redis
            setmeal = setMealDao.selectById(id);
            String findOrderJson = mapper.writeValueAsString(setmeal);
            jedis.sadd("healthOrder",findOrderJson);
        } catch (IOException e) {
            log.error("",e);
        }
        return setmeal;
    }
}
